package jobs.job3.classloaderdemo.server.zkutil;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ZkClientDemo {


    ZkClient zkClient;

    public ZkClientDemo() {
        zkClient = new ZkClient();
        zkClient.connectZk();
    }

    private  void sendRequest() throws IOException {
        Random rnd = new Random();
        List<String> serverInfos = zkClient.getServerInfos();
        String info = serverInfos.get(rnd.nextInt(serverInfos.size()));
        String[] ipPort = info.split(":");
        Socket socket = new Socket(ipPort[0], Integer.parseInt(ipPort[1]));
        InputStream in = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int n = in.read(bytes);
        System.out.println("从服务器" + info + "返回的时间为: " + new String(bytes, 0, n));
        in.close();
        socket.close();
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        ZkClientDemo zkClient = new ZkClientDemo();
        while (true) {
            zkClient.sendRequest();
            Thread.sleep(1000);
        }
    }
}
